using System;
using System.IO;
using System.Xml;

namespace ECCIT.Configuration
{
	/// <summary>
	/// 
	/// </summary>
	[Serializable]
	public class ConfigManager
	{
		private const string DIRECTORY = "Configuration";
		private string _physicalPath;
		private string _configFileName;

		public string PhysicalPath
		{
			get{ return _physicalPath; }
		}

		public string ConfigFileName
		{
			get{ return _configFileName; }
			set{ _configFileName = value; }
		}

		public ConfigManager(){}

		public ConfigManager(string applicationPath)
		{
			string physicalPath = GetConfigPath(applicationPath);
			_physicalPath = physicalPath;			
		}

		public ConfigManager(string applicationPath, string configFileName)
		{			
			string physicalPath = GetConfigPath(applicationPath);
			_physicalPath = physicalPath;			
			_configFileName = configFileName;
		}

		private string GetConfigPath(string applicationPath)
		{
			if( !applicationPath.EndsWith("\\") )
				applicationPath += "\\";
			
			string absPath = applicationPath + DIRECTORY + "\\";
			return absPath;
		}

		public virtual XmlDocument GetConfigDocument()
		{
			string configPath = _physicalPath + _configFileName;
			XmlDocument configDoc = new XmlDocument();
			if( File.Exists(configPath) )
			{				
				try
				{
					configDoc.Load(configPath);					
				}
				catch(Exception e)
				{
					string message = "The xml file: " + _configFileName + " underneath " + configPath + " doesn't have good xml format.";
					throw new Exception(message, e);
				}				
			}
			else
			{
				string message = "This file has not been found : " + _configFileName + ". Location: " + configPath;
				throw new FileNotFoundException(message, configPath);
			}		

			return configDoc;
		}
	}
}
